package com.huaxinkaiye.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.toolbox.NetworkImageView;
import com.google.gson.Gson;
import com.huaxinkaiye.R;
import com.huaxinkaiye.application.HuaXinApplication;
import com.huaxinkaiye.bean.ListBean;
import com.huaxinkaiye.bean.PictureRows;
import com.huaxinkaiye.lookbigphoto.PhotosDialog;
import com.huaxinkaiye.utils.FileImageUpload;
import com.huaxinkaiye.utils.ImageUtils;
import com.huaxinkaiye.utils.PhotoImplActivity;
import com.huaxinkaiye.utils.MySharedPreferences;
import com.huaxinkaiye.utils.ProgressUtil;
import com.huaxinkaiye.utils.SimpleClient;
import com.huaxinkaiye.utils.ToastUtil;
import com.huaxinkaiye.utils.UrlUtils;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class JianDangActivity extends PhotoImplActivity implements
		OnClickListener, OnLongClickListener {
	private ImageView im_queren, im_home;
	private NetworkImageView im_photo;
	private TextView te_photo;
	private EditText te_chepaihao, te_beizhu;
	TextView te_chepaiyanse, te_cheshenyanse;
	Spinner spinner, cs_spinner;
	public List<NameValuePair> params;
	public ProgressUtil progress;
	public JSONArray jsonarray0, jsonarray1;
	public List<Map<String, Object>> data, data2;
	public Map<String, Object> map;
	public int cheshenid, chepaiid;
	public JSONArray array;
	public ListBean listbean;
	public String picUrldata;
	public int carid = 0;
	public String carID;
	public String localPicPath = "";
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				JiexiData0(msg.obj.toString());
				break;
			case 1:
				JiexiData(msg.obj.toString());
				break;
			case 2:
				progress.dismiss();
				SaveData(msg.obj.toString());
				break;
			case 4:
				jiexipicture(msg.obj.toString());
				break;
			case 3:
				progress.dismiss();
				jiexipictureData(msg.obj.toString());
				break;
			case 5:
				jiexichujianListData(msg.obj.toString());
				break;
			case 6:
				carID = msg.obj.toString();
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_jiandang);
		progress = new ProgressUtil(this, "正在保存数据");
		initView();
	}

	protected void jiexichujianListData(String s) {
		// TODO Auto-generated method stub
		JSONObject json;
		try {
			json = new JSONObject(s);
			// Log.e("s.substring(558, 585)", s.substring(500, 580));
			Gson gson = new Gson();
			listbean = gson.fromJson(s, ListBean.class);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@SuppressLint("NewApi")
	protected void jiexipicture(String string) {
		// TODO Auto-generated method stub
		try {
			JSONObject json = new JSONObject(string);
			picUrldata = string;
			Gson gson = new Gson();
			PictureRows pr = gson.fromJson(string, PictureRows.class);
			im_photo.setImageUrl(UrlUtils.host
					+ pr.getRows().get(0).getFilepath(),
					HuaXinApplication.mImageLoader);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	protected void jiexipictureData(String string) {
		// TODO Auto-generated method stub
		Log.e("picture_data", string);
		try {
			JSONObject json = new JSONObject(string);
			if (json.getBoolean("isSuccess")) {
				ToastUtil.show(this, json.getString("message"));
				getPictureId();
			} else {
				ToastUtil.show(this, json.getString("message"));
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	protected void SaveData(String s) {
		// TODO Auto-generated method stub
		try {
			JSONObject json = new JSONObject(s);
			if (json.getBoolean("isSuccess")) {
				ToastUtil.show(this, json.getString("message") + "请上传车牌照片");
				Log.e("save_data", s);
				Message mes = new Message();
				mes.what = 6;
				mes.obj = json.getString("id");
				handler.sendMessage(mes);
				// te_chepaihao.setText("");
				// te_beizhu.setText("");
				// refresh(1);
				// getPictureId();
			} else {
				ToastUtil.show(this, json.getString("message"));
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void getPictureId() {
		// TODO Auto-generated method stub
		if (HuaXinApplication.isNetWorkConnected()) {
			params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("cid", carID + ""));
			new Thread() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					super.run();
					try {
						String data = SimpleClient.doPost(
								UrlUtils.picturelist_url, params);
						Log.e("picture_data", data);
						Message mes = new Message();
						mes.what = 4;
						mes.obj = data;
						handler.sendMessage(mes);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}.start();
		} else {
			Toast.makeText(this, "网络异常", Toast.LENGTH_SHORT).show();
		}
	}

	private void initView() {
		// TODO Auto-generated method stub
		im_queren = (ImageView) findViewById(R.id.im_queren);
		im_queren.setOnClickListener(this);
		im_home = (ImageView) findViewById(R.id.im_home);
		im_home.setOnClickListener(this);
		im_photo = (NetworkImageView) findViewById(R.id.im_photo);
		im_photo.setOnClickListener(this);
		im_photo.setOnLongClickListener(this);
		te_photo = (TextView) findViewById(R.id.te_photo);
		te_photo.setOnClickListener(this);
		te_chepaihao = (EditText) findViewById(R.id.te_chepaihao);
		//te_chepaiyanse = (TextView) findViewById(R.id.te_chepaiyanse);
		//te_cheshenyanse = (TextView) findViewById(R.id.te_cheshenyanse);
		te_beizhu = (EditText) findViewById(R.id.te_beizhu);
		spinner = (Spinner) findViewById(R.id.lq_spinner);
		cs_spinner = (Spinner) findViewById(R.id.cs_spinner);
		InitchepaiSpinnerData();
		InitcheshenSpinnerData();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.im_home:
			im_photo.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.home));
			te_chepaihao.setText("");
			te_beizhu.setText("");
			break;
		case R.id.im_queren:
			jianDang();
			break;
		case R.id.te_photo:
			// jiexiphoto();
			break;
		case R.id.im_photo:
			// 查看大图
			lookBigImage();
			break;
		}
	}

	private void jiexiphoto() {
		// TODO Auto-generated method stub
		new Thread() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
			}
		}.start();
	}

	private void jianDang() {
		// TODO Auto-generated method stub
		if (HuaXinApplication.isNetWorkConnected()) {
			if (te_chepaihao.getText().toString().equals("")) {
				ToastUtil.show(this, "车牌号不为空");
				return;
			}
			if (te_chepaiyanse.getText().toString().equals("")) {
				ToastUtil.show(this, "车牌颜色不为空");
				return;
			}
			if (te_cheshenyanse.getText().toString().equals("")) {
				ToastUtil.show(this, "车身颜色不为空");
				return;
			}
			if (te_chepaiyanse.getText().toString()
					.equals(te_cheshenyanse.getText().toString())) {
				ToastUtil.show(this, "车身车牌颜色不能相同");
				return;
			}
			for (int i = 0; i < jsonarray0.length(); i++) {
				JSONObject json;
				try {
					json = new JSONObject(jsonarray0.get(i).toString());
					if (json.getString("name").equals(
							te_cheshenyanse.getText().toString().trim())) {
						cheshenid = json.getInt("id");
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			for (int i = 0; i < data2.size(); i++) {
				JSONObject json;
				try {
					json = new JSONObject(jsonarray1.get(i).toString());
					if (json.getString("name").equals(
							te_chepaiyanse.getText().toString().trim())) {
						chepaiid = json.getInt("id");
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			Log.e("idididi", cheshenid + "---" + chepaiid);
			progress.show();
			params = new ArrayList<NameValuePair>();
			// params.add(new BasicNameValuePair("id", ""));
			// params.add(new BasicNameValuePair("archivesStatus.id", "1"));
			// params.add(new BasicNameValuePair("valueBrand.id", "1"));
			// params.add(new BasicNameValuePair("valueSeries.id", "1"));
			// params.add(new BasicNameValuePair("valueModel.id", "1"));
			params.add(new BasicNameValuePair("plateNumber", te_chepaihao
					.getText().toString()));
			params.add(new BasicNameValuePair("carBodyColorId", cheshenid + ""));
			params.add(new BasicNameValuePair("material.id", chepaiid + ""));
			params.add(new BasicNameValuePair("filingMemo", te_beizhu.getText()
					.toString()));
			new Thread() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					super.run();
					try {
						String data = SimpleClient.doPost(
								UrlUtils.jiandang_url, params);
						Log.e("jiandang_data", data);
						Message mes = new Message();
						mes.what = 2;
						mes.obj = data;
						handler.sendMessage(mes);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						progress.dismiss();
						e.printStackTrace();
					}
				}
			}.start();
		} else {
			Toast.makeText(JianDangActivity.this, "网络异常", Toast.LENGTH_SHORT)
					.show();
		}
		// String url=UrlUtils.jiandang_url
		// + "&id=" + ""
		// + "&archivesStatus.id="+ "14"
		// + "&plateNumber="+ "川a"
		// + "&carBodyColor.id=" + "4"
		// + "&material.id="+"5"
		// + "&filingMemo="+"测试";
		// + password.getText().toString();

		// if (HuaXinApplication.isNetWorkConnected()) {
		// new PostTaskUtil(this) {
		//
		// @Override
		// public void callBack(String re) {
		// // TODO Auto-generated method stub
		// Log.e("jiangdang_data",re );
		// }
		// }.execute(UrlUtils.jiandang_url,"id=" , "",
		// "archivesStatus.id=","14",
		// "plateNumber=", "川a",
		// "carBodyColor.id=","4",
		// "material.id=","5",
		// "filingMemo=","测试");
		// } else {
		// Toast.makeText(JianDangActivity.this, "网络异常", Toast.LENGTH_SHORT)
		// .show();
		// }
	}

	@Override
	public boolean onLongClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.im_photo:
			showPopupMenu(im_photo, true, "jiandang");
			break;
		}
		return true;
	}

	@Override
	public void doAfterZoom(Bitmap bitmap) {
		// TODO Auto-generated method stub
		im_photo.setImageBitmap(ImageUtils.createFramedPhoto(bitmap));
		uploadphoto(bitmap);
	}

	private void uploadphoto(final Bitmap bitmap) {
		// TODO Auto-generated method stub
		im_photo.setImageBitmap(ImageUtils.createFramedPhoto(bitmap));
		String localPicPath = ImageUtils.savePicToCache(JianDangActivity.this,
				bitmap);
		// File mCurrentPhotoFile = new File(localPicPath);
		// for(int i=0;i<listbean.getRows().size();i++){
		// if(listbean.getRows().get(i).getPlateNumber().endsWith(te_chepaihao.getText().toString())){
		// carid=listbean.getRows().get(i).getId();
		// }
		// //
		// if(jo.getString("plateNumber").endsWith(te_chepaihao.getText().toString())){
		// // fileType=jo.getInt("id")+"";
		// // }
		// }
		Log.e("carID", carID + "");
		params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("id", carID + ""));
		params.add(new BasicNameValuePair("fileType", "1"));
		params.add(new BasicNameValuePair("pictureFile", localPicPath));
		final String url = UrlUtils.picture_url;
		progress.show();
		new Thread() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				String localPicPath = ImageUtils.savePicToCache(
						JianDangActivity.this, bitmap);
				// File mCurrentPhotoFile = new File(localPicPath);
				Log.e("localPicPath", localPicPath);
				Log.e("url", url);
				String result = FileImageUpload.postFile(url, params);
				Message message = new Message();
				message.what = 3;
				message.obj = result;
				handler.sendMessage(message);
			}
		}.start();
	}

	// 获取图片id
	protected void refresh(int pageNo) {
		// TODO Auto-generated method stub
		pageNo = 1;
		params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("pageNo", 1 + ""));
		params.add(new BasicNameValuePair("pageSize", 1 + ""));
		params.add(new BasicNameValuePair("sort", "id"));
		params.add(new BasicNameValuePair("direction", "desc"));
		params.add(new BasicNameValuePair("plateNumber", ""));
		// params.add(new BasicNameValuePair("recordNo","recordNo"));
		new Thread() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				String data;
				try {
					data = SimpleClient
							.doPost(UrlUtils.chujianlist_url, params);
					Log.e("chujianlist_data", data);
					Message mes = new Message();
					mes.what = 5;
					mes.obj = data;
					handler.sendMessage(mes);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}.start();
	}

	protected void lookBigImage() {
		// TODO Auto-generated method stub
		final ArrayList<String> urllist = new ArrayList<String>();
		Gson gson = new Gson();
		Log.e("picUrldata", picUrldata);
		PictureRows pr = gson.fromJson(picUrldata, PictureRows.class);
		for (int i = 0; i < pr.getRows().size(); i++) {
			urllist.add(UrlUtils.host + pr.getRows().get(i).getFilepath());
		}
		new PhotosDialog(JianDangActivity.this, R.style.Dialog)
				.show(0, urllist);
	}

	protected void JiexiData0(String cheshenyanse) {
		// TODO Auto-generated method stub
		data2 = new ArrayList<Map<String, Object>>();
		Log.e("cheshenyanse---", cheshenyanse);
		try {
			jsonarray0 = new JSONArray(cheshenyanse);
			for (int i = 0; i < jsonarray0.length(); i++) {
				JSONObject json = new JSONObject(jsonarray0.get(i).toString());
				map = new HashMap<String, Object>();
				map.put("text", json.get("name").toString());
				data2.add(map);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		SimpleAdapter simpleAdapter = new SimpleAdapter(this, data2,
				R.layout.spinner, new String[] { "text" },
				new int[] { R.id.textView1 });
		// 设置显示的数据
		cs_spinner.setAdapter(simpleAdapter);
		// 注册事件
		cs_spinner
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

					@Override
					public void onNothingSelected(AdapterView<?> parent) {
						Toast.makeText(getApplicationContext(), "没有改变的处理",
								Toast.LENGTH_LONG).show();
					}

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						Spinner spinner = (Spinner) arg0;
						te_cheshenyanse.setText(spinner
								.getItemAtPosition(arg2)
								.toString()
								.substring(
										6,
										spinner.getItemAtPosition(arg2)
												.toString().length() - 1));
					}
				});
	}

	private void InitcheshenSpinnerData() {
		// TODO Auto-generated method stub
		if (HuaXinApplication.isNetWorkConnected()) {
			String url = UrlUtils.chepaiyanshe + "parentId=1";
			Log.e("cheshenyanse_url", url);
			params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("parentId", "1"));
			new Thread() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					super.run();
					String data;
					try {
						data = SimpleClient.doPost(UrlUtils.chepaiyanshe,
								params);
						MySharedPreferences.getInstance(JianDangActivity.this)
								.setString("cheshenyanse", data);
						Log.e("cheshenyanse", data);
						Message message = new Message();
						message.what = 0;
						message.obj = data;
						handler.sendMessage(message);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}.start();
		} else {
			Toast.makeText(this, "网络异常", Toast.LENGTH_SHORT).show();
		}
	}

	private void InitchepaiSpinnerData() {
		// TODO Auto-generated method stub
		if (HuaXinApplication.isNetWorkConnected()) {
			String url = UrlUtils.chepaiyanshe + "parentId=2";
			Log.e("chepaiyanse_url", url);
			params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("parentId", "2"));
			new Thread() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					super.run();
					String data;
					try {
						data = SimpleClient.doPost(UrlUtils.chepaiyanshe,
								params);
						MySharedPreferences.getInstance(JianDangActivity.this)
								.setString("chepaiyanse", data);
						Log.e("chepaiyanse", data);
						Message message = new Message();
						message.what = 1;
						message.obj = data;
						handler.sendMessage(message);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}.start();
		} else {
			JiexiData(MySharedPreferences.getInstance(this).getString(
					"chepaiyanse"));
			Toast.makeText(this, "网络异常", Toast.LENGTH_SHORT).show();
		}
	}

	protected void JiexiData(String chepaiyanse) {
		// TODO Auto-generated method stub
		data = new ArrayList<Map<String, Object>>();
		Log.e("chepaiyanse---", chepaiyanse);
		try {
			jsonarray1 = new JSONArray(chepaiyanse);
			for (int i = 0; i < jsonarray1.length(); i++) {
				JSONObject json = new JSONObject(jsonarray1.get(i).toString());
				map = new HashMap<String, Object>();
				map.put("text", json.get("name").toString());
				data.add(map);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		SimpleAdapter simpleAdapter = new SimpleAdapter(this, data,
				R.layout.spinner, new String[] { "text" },
				new int[] { R.id.textView1 });
		// 设置显示的数据
		spinner.setAdapter(simpleAdapter);
		// 注册事件
		spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				Toast.makeText(getApplicationContext(), "没有改变的处理",
						Toast.LENGTH_LONG).show();
			}

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				Spinner spinner = (Spinner) arg0;
				te_chepaiyanse.setText(spinner
						.getItemAtPosition(arg2)
						.toString()
						.substring(
								6,
								spinner.getItemAtPosition(arg2).toString()
										.length() - 1));
			}
		});
	}
}
